/*******************************************************
> Copyright (C) 2024 ==iot== All rights reserved.
> File Name: server.c
> Author: wyf
> Created Time: 2024年08月13日 星期二 13时44分16秒
***************************************************/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h> //目录名获取配合DIR
#include <assert.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h> //文件控制操作
#include <sys/types.h> //获取pid等
#include <sys/wait.h> //等待子进程结束
#include <time.h> //时间获取
#include <sys/ipc.h> //进程通信
#include <sys/msg.h> //消息队列
#include <sys/shm.h> //共享内存
#include <signal.h> //信号处理
#include <pthread.h> //线程
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

struct head
{
	int type;
	char mean[10];
};

struct exam
{
	int data1;
	int data2;
};

struct result
{
	int res;
};

int main(int argc, const char* argv[])
{
	char buf[1024] = { 0 };
	//创建套接字
	int sock = 0;
	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock == -1) {
		perror("socket");
	}

	int ret = 0;
	//绑定地址
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = 5494;
	addr.sin_addr.s_addr = inet_addr("192.168.48.128");
	bind(sock, (struct sockaddr*)&addr, sizeof(addr));

	//接收客户端的信息
	struct sockaddr_in client;
	int len = sizeof(client);
	
	ret = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr*)&client, &len);
	if (ret == -1) {
		perror("recvfrom");
	}



	//加法
	struct head* p = (struct head*)buf;
	if (p->type == 1) {
		struct exam* q = NULL;
		q = (struct exam*)(buf + sizeof(struct head));
		struct result re;
		re.res = (q->data1 + q->data2);
		printf("res = %d\n", re.res);
		sendto(sock, &re, sizeof(re), 0, (struct sockaddr*)&client, sizeof(struct sockaddr));
		close(sock);
	}
	else if (p->type == 2) {
		struct exam* q = NULL;
		q = (struct exam*)(buf + sizeof(struct head));
		struct result re;
		re.res = (q->data1 - q->data2);
		printf("res = %d\n", re.res);
		sendto(sock, &re, sizeof(re), 0, (struct sockaddr*)&client, sizeof(struct sockaddr));
		close(sock);
	}
	else if (p->type == 3) {
		struct exam* q = NULL;
		q = (struct exam*)(buf + sizeof(struct head));
		struct result re;
		re.res = (q->data1) * (q->data2);
		printf("res = %d\n", re.res);
		sendto(sock, &re, sizeof(re), 0, (struct sockaddr*)&client, sizeof(struct sockaddr));
		close(sock);
	}
	else if (p->type == 4) {
		struct exam* q = NULL;
		q = (struct exam*)(buf + sizeof(struct head));
		struct result re;
		re.res = (q->data1) / (q->data2);
		printf("res = %d\n", re.res);
		sendto(sock, &re, sizeof(re), 0, (struct sockaddr*)&client, sizeof(struct sockaddr));
		close(sock);
	}


    return 0;

}


